<template>
  <div class="container" style="width: 99%;margin-top: -25px;">
    <!-- 工具栏 -->
    <div class="toolbar" style="float: left;padding-top: 10px;padding-left: 15px">
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <blog-button :label="$t('action.search')" perms="sys:role:view" type="primary" @click="findPage(null)"></blog-button>
        </el-form-item>
        <el-form-item>
          <blog-button :label="$t('action.add')" perms="sys:user:add" type="primary" @click="handleAdd"></blog-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格内容栏 -->
    <blog-table permsEdit="sys:user:edit" persmDelete="sys:user:delete"
    :data="pageResult" :columns="columns"
    @findPage="findPage" @handleEdit="handleEdit" @handleDelete="handleDelete">
    </blog-table>
    <!-- 新增编辑界面 -->
    <el-dialog :title="operation?'新增':'编辑'" width="40%" :visible.sync="dialogVisible" :colse-on-click-model="false">
      <el-form :model="dataForm" label-width="80px" :rules="dataFormRules" ref="dataForm" :size="size" label-position="right">
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input v-model="dataForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="dataForm.password" type="password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="机构" prop="deptName">
          <popup-tree-input
          :data="deptData"
          :props="deptTreeProps"
          :prop="dataForm.deptName"
          :nodeKey="''+dataForm.deptId"
          :currentChangeHandle="deptTreeCurrentChangeHandle">
          </popup-tree-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="dataForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="dataForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="userRoles" v-if="!operation">
          <el-select v-model="dataForm.userRoles" multiple placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.remark"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="size" @click.native="dialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button :size="size" type="primary" @click.native="submitForm" :loading="editLoading">{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import PopupTreeInput from "@/components/PopupTreeInput"
  import BlogButton from "@/views/Core/BlogButton"
  import BlogTable from "@/views/Core/BlogTable"

  export default {
    components: {
      BlogButton,
      BlogTable,
      PopupTreeInput
    },
    name: 'Home',
    data() {
      return {
        size: 'small',
        filters: {
          name: ''
        },
        columns: [
          {prop: "id", label: "ID", minWidth: 50},
          {prop: "name", label: "用户名", minWidth: 120},
          {prop: "deptName", label: "机构", minWidth: 120},
          {prop: "roleNames", label: "角色", minWidth: 100},
          {prop: "email", label: "邮箱", minWidth: 120},
          {prop: "mobile", label: "手机", minWidth: 100},
          {prop: "status", label: "状态", minWidth: 70}
          // {prop:"createBy", label:"创建人", minWidth:120},
          // {prop:"createTime", label:"创建时间", minWidth:120, formatter:this.dateFormat}
          // {prop:"lastUpdateBy", label:"更新人", minWidth:100},
          // {prop:"lastUpdateTime", label:"更新时间", minWidth:120, formatter:this.dateFormat}
        ],
        pageRequest: {pageNum: 1, pageSize: 8},
        pageResult: {},
        operation: false, // true:新增, false:编辑
        dialogVisible: false, // 新增编辑界面是否显示
        editLoading: false,
        dataFormRules: {
          name: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ]
        },
        // 新增编辑界面数据
        dataForm: {
          id: 0,
          name: '',
          password: '123456',
          deptId: 1,
          deptName: '',
          email: 'test@qq.com',
          mobile: '13889700023',
          status: 1,
          userRoles: []
        },
        deptData: [],
        deptTreeProps: {
          label: 'name',
          children: 'children'
        },
        roles: []
      }
    },
    methods: {
      findPage: function (data) {
        if(data !== null) {
          this.pageRequest = data.pageRequest;
        }
        this.pageRequest.columnFilters = {name:{name: 'name', value: this.filters.name}}
        this.$api.user.findPage(this.pageRequest).then((res) => {
          this.pageResult = res.data
          this.findUserRoles()
        }).then(data!=null?data.callback:'')
      },
      findUserRoles: function () {
        this.$api.role.findAll().then((res) => {
          //加载角色
          this.roles = res.data
        })
      },
      handleDelete: function (data) {
        this.$api.user.batchDelete(data.params).then(data!=null?data.callback:'')
      },
      // 显示新增界面
      handleAdd: function () {
        this.dialogVisible = true
        this.operation = true
        this.dataForm = {
          id: 0,
          name: '',
          password: '',
          deptId: 1,
          deptName: '',
          email: 'test@qq.com',
          mobile: '13889700023',
          status: 1,
          userRoles: []
        }
      },
      // 显示编辑界面
      handleEdit: function (params) {
        this.dialogVisible = true
        this.operation = false
        this.dataForm = Object.assign({}, params.row)
        let userRoles = []
        for(let i=0,len=params.row.userRoles.length; i<len; i++) {
          userRoles.push(params.row.userRoles[i].roleId)
        }
        this.dataForm.userRoles = userRoles
      },
      // 编辑
      submitForm: function () {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.editLoading = true
              let params = Object.assign({}, this.dataForm)
              let userRoles = []
              for(let i=0,len=params.userRoles.length; i<len; i++) {
                let userRole = {
                  userId: params.id,
                  roleId: params.userRoles[i]
                }
                userRoles.push(userRole)
              }
              params.userRoles = userRoles
              this.$api.user.save(params).then((res) => {
                this.editLoading = false
                if(res.code == 200) {
                  this.$message({ message: '操作成功', type: 'success' })
                  this.dialogVisible = false
                  this.$refs['dataForm'].resetFields()
                } else {
                  this.$message({message: '操作失败, ' + res.msg, type: 'error'})
                }
                this.findPage(null)
              })
            })
          }
        })
      },
      // 获取部门列表
      findDeptTree: function () {
        this.$api.dept.findDeptTree().then((res) => {
          this.deptData = res.data
        })
      },
      // 菜单树选中
      deptTreeCurrentChangeHandle (data, node) {
        this.dataForm.deptId = data.id
        this.dataForm.deptName = data.name
      },
      // 时间格式化
      dateFormat: function (row, column, cellValue, index){
        return format(row[column.property])
      }
    },
    mounted() {
      this.findDeptTree()
    }
  }
</script>
